var socket;

var count = 0;
function connect() {
    var host = "ws://" + $("serverIP").value + ":" + $("serverPort").value + "/"
    socket = new WebSocket(host);
    socket.binaryType = 'arraybuffer' //arraybuffer blob
    try {

        socket.onopen = function (msg) {
            $("btnConnect").disabled = true;

            console.log("链接成功..")
        };

        socket.onmessage = function (msg) {
            console.log(" onmessage msg.data", msg.data)
            var n = msg.data.constructor.name;

            if (typeof msg.data == "string") {

            }else if (n == 'ArrayBuffer') {
               
                var bf = msg.data
                console.log("接收到的ArrayBuffer消息..", bf.byteLength)
                count++;
                
                //通过dataView读取Buffer内容 
                var dv = new DataView(bf); 
                var protoId = dv.getInt32(0, true) //需要小端读取 否则读取到的数值和服务器的不符
                console.log('----------- 读取到服务器发送回来的结果 11: protoId', protoId,"第",count,"个数据")
                                
                //使用protobuf协议进行通讯
                bufRet = ProtoUtils.decode("CopyInfo",bf.slice(4)) //前4个字节是消息id需要截取出来,解码protobuf数据
                console.log("接收到protobuf数据bufRet",bufRet);
                return;
                
                
                //自己设置读取数据
                dv = new DataView(bf.slice(4));                
                var inf = get_proto_Inf(protoId);
                console.log("inf:",inf)
                if (inf && inf['fn']) {
                    inf['fn'](dv);
                }
                

                //把buffer数据转换成Blob对象
                //var b = new Blob([bf])                
                //parseBlob(b) //再通过blob读取
            } else if (n == 'Blob') {
                console.log("Blob 消息..")
                //parseBlob(msg.data)
            }
        };

        socket.onclose = function (msg) {
            $("btnConnect").disabled = false;
            console.log("socket closed!")
        };
    }
    catch (ex) {
        log(ex);
    }

}

function getMessageBuffer(idx,msg,isForce) {
    let buf;
    let info;
    if (idx%2==0 || isForce) {
        //返回copyinfo
        info = ProtoUtils.create("CopyInfo");
        info.code = 10001;
        info.progress = 20001+idx;
        info.desc = msg;        
    }else{
        //返回CopyReward
        info = ProtoUtils.create("CopyReward");
        info.itemId = 1021003;
        info.title = "副本奖励";
        info.count = 4;
        info.desc = "丰富的奖励来自你个人的努力";
        
    }
    buf = info.toBuffer();
    console.log("构建了结构:",info);    
    return buf;
}

function send() {
    if (socket) {
        
        var msg = $("sendText").value
        console.log("---------00-msg", msg, msg.length)
        var buffer = new ArrayBuffer(8);
        this.count = 0;
        var protoId = new Int32Array(buffer, 0, 2);
        protoId[0] = 10001;
        protoId[1] = 61111;
        
        //var userId = new Int32Array(buffer, 4);
        //userId[0] = 59999;
        
        let count = $("sendCount").value;

        /*
        //使用二进制发送数据 执行以下代码
        console.log("send protoId xx:", protoId);
        var blob = new Blob([buffer, msg,"哈哈"], { type: 'application/octet-stream' });  //,{type:"text/plain"}        
        count = parseInt(count); //连续发生多少条数据
        for (let index = 0; index < count; index++) {
            console.log("******* blob.size ***** ",blob.size);            
            socket.send(blob);
        }
        console.log("发送数据包 count:",count);
        */
        
        //使用protobuf发送 执行以下代码
        for (let index = 0; index < count; index++) {
            /*
            let info = ProtoUtils.create("CopyInfo");
            info.code = 10001;
            info.progress = 60001+index;
            info.desc = msg;        
            console.log("info 201",info);
            let buf = info.toBuffer();
            */
            let buf = getMessageBuffer(index,msg);
            console.log("--- 结构体数据 buf",buf,buf.length);
            let idBuf = new ArrayBuffer(4);
            var protoId = new Int32Array(idBuf,0,1);
            protoId[0] = 15000+index;
            var blob = new Blob([idBuf,buf], { type: 'application/octet-stream' });
            console.log("******* 发送 blob.size ***** ",blob.size);   
            socket.send(blob);
        }
                

    } else {
        alert("请先连接服务器")
    }

}



window.onbeforeunload = function () {
    try {
        socket.close();
        socket = null;
    }
    catch (ex) {
    }
};

window.onload = () => {

    //测试客户端写二进制数据

    var buffer = new ArrayBuffer(6) //参数是字节数 不是位数,现在想储存一个16位和一个32为的int  
    var dataView = new DataView(buffer)

    dataView.setInt16(0, 199)
    dataView.setInt32(2, 29999)

    /*
    var int16 = new Int16Array(buffer,0,1)  //Int16Array.BYTES_PER_ELEMENT 每个元素需要多少个字节
    int16[0] = 100;   
    var int32 = new Int32Array(buffer,2)
    int32[0] = 29999;
    console.log('int16',int16,'int32',int32)
    console.log("Int16Array.BYTES_PER_ELEMENT",
    Int16Array.BYTES_PER_ELEMENT,'int16.byteOffset,int16.byteLength',
    int16.byteOffset,int16.byteLength)
    */




    var b = new Blob([buffer, '你好 这是文本']) //ArrayBuffer、ArrayBufferView、Blob、DOMString.
    console.log('b.slice',
        new Int16Array(dataView.buffer.slice(0, 2)),
        dataView.getInt16(0),
        dataView.getInt32(2))
    //parseBlob(b)


}

function $(id) { return document.getElementById(id); }

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function displayContent(msg) {
    $("txtContent").value += "\r\n" + new Date().Format("yyyy/MM/dd hh:mm:ss") + ":  " + msg;
}
function onkey(event) { if (event.keyCode == 13) { send(); } }


